package org.dy.db.model;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

public class CachedModel {
	// file path
	static final String configDir = "config";
	static final String dataFieldDir = "cache";
	
	private String baseDir;
	
	private String name;
	private String module;
	private String app;
	
	protected TableHeader th;
	protected TableLayer tl;
	
	public CachedModel(String baseDir) {
		this.baseDir = baseDir;
	}
	
	public CachedModel(String baseDir, String app, String module, String name) {
		super();
		this.baseDir = baseDir;
		this.name = name;
		this.module = module;
		this.app = app;
	}

	
	private String getFilePath(String dir){
		return baseDir + "/" + dir + "/" + app + "/" + module + "/" + name + ".xml";
	}
	
	private void outputCacheFile(Element el) throws IOException{
		XMLOutputter outp = new XMLOutputter();
		Format format = Format.getPrettyFormat();
		format.setIndent("	");
		outp.setFormat(format);
        
        Document doc = new Document();
        doc.setRootElement(el);
        String targetFilePath = getFilePath(dataFieldDir);
        FileUtils.touch(new File(targetFilePath));
		outp.output(doc, new FileOutputStream(targetFilePath));
	}
	
	public void loadFieldInfo(){
		File configFile = new File(getFilePath(configDir));
		File cachedFile = new File(getFilePath(dataFieldDir));
		
		Parser parser = new Parser(configFile, cachedFile);
		
		th = parser.loadTableHeader();
		tl = parser.loadTableLayer(new File(configDir));
		
		// cache it if the cache file not exist
		if(!cachedFile.exists()){
			try {
				outputCacheFile(th.getXmlElement());
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}			
		}
	}
	
	public String getApp() {
		return app;
	}
	public void setApp(String app) {
		this.app = app;
	}
	public String getModule() {
		return module;
	}
	public void setModule(String module) {
		this.module = module;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}

	public TableHeader getTh() {
		return th;
	}

	public void setTh(TableHeader th) {
		this.th = th;
	}
	
	public String getDes(){
		return this.th.getDes();
	}

}
